package com.example.myapplication

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.myapplication.ui.theme.MyApplicationTheme

@Composable
fun MainScreen(
    modifier: Modifier = Modifier,
    onStartClick: (Double, Double) -> Unit,
    onEndClick: () -> Unit,
    initialHistory: List<HistoryItem> = emptyList(),
    onSaveHistory: (String, String) -> Unit,
    onDeleteHistory: (Long) -> Unit
) {
    var inputLat by remember { mutableStateOf("30.506243") } // Default latitude
    var inputLon by remember { mutableStateOf("114.40867") } // Default longitude
    var isRunning by remember { mutableStateOf(false) }
    val history = remember { mutableStateListOf<HistoryItem>() }

    // 初始化历史记录
    LaunchedEffect(initialHistory) {
        history.clear()
        history.addAll(initialHistory)
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        TextField(
            value = inputLat,
            onValueChange = { inputLat = it },
            label = { Text("Latitude") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        TextField(
            value = inputLon,
            onValueChange = { inputLon = it },
            label = { Text("Longitude") },
            modifier = Modifier.fillMaxWidth()
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(onClick = {
            if (isRunning) {
                onEndClick()
                isRunning = false
            } else {
                val lat = inputLat.toDoubleOrNull()
                val lon = inputLon.toDoubleOrNull()
                if (lat != null && lon != null) {
                    val existingItem = history.find { it.latitude == inputLat && it.longitude == inputLon }
                    if (existingItem == null) {
                        val newItem = HistoryItem(0, inputLat, inputLon) // id为0，在插入数据库时会生成新的id
                        history.add(0, newItem) // 新记录插入到首位
                        onSaveHistory(inputLat, inputLon) // 保存到数据库
                    }
                    onStartClick(lat, lon)
                    isRunning = true
                }
            }
        }) {
            Text(if (isRunning) "End" else "Start")
        }
        Spacer(modifier = Modifier.height(16.dp))

        LazyColumn {
            items(history) { item ->
                HistoryItem(item, onDeleteHistory = { id ->
                    onDeleteHistory(id)
                    history.remove(item) // 从UI中删除
                }) {
                    inputLat = it.latitude
                    inputLon = it.longitude
                }
            }
        }
    }
}

@Composable
fun HistoryItem(item: HistoryItem, onDeleteHistory: (Long) -> Unit, onClick: (HistoryItem) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp)
            .clickable { onClick(item) },
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = "Lat: ${item.latitude}, Lon: ${item.longitude}")
        OutlinedButton(
            onClick = { onDeleteHistory(item.id) },
            colors = ButtonDefaults.outlinedButtonColors(contentColor = Color.Red),
            contentPadding = PaddingValues(0.dp),
            modifier = Modifier
                .height(24.dp)
                .width(50.dp)
        ) {
            Text(
                text = "Del",
                color = Color.Red,
                fontSize = 12.sp,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
    MyApplicationTheme {
        MainScreen(onStartClick = { _, _ -> }, onEndClick = {}, initialHistory = emptyList(), onSaveHistory = { _, _ -> }, onDeleteHistory = {})
    }
}
